﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity.Infrastructure.Interception;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Sharp.Domain.Repository.EF
{
    /// <summary>
    /// NoLock拦截器
    /// </summary>
    public class MsSqlNoLockInterceptor : DbCommandInterceptor
    {
        private static readonly Regex TableAliasRegex =
            new Regex(@"(?<tableAlias>AS \[Extent\d+\](?! WITH \(NOLOCK\)))",
                RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled);
        /// <summary>
        /// NoLock拦截器
        /// </summary>
        public MsSqlNoLockInterceptor()
        {
            SuppressNoLock = true;
        }
        /// <summary>
        /// SuppressNoLock
        /// </summary>
        [ThreadStatic]
        public static bool SuppressNoLock;
        /// <summary>
        /// ScalarExecuting
        /// </summary>
        /// <param name="command"></param>
        /// <param name="interceptionContext"></param>
        public override void ScalarExecuting(DbCommand command,
            DbCommandInterceptionContext<object> interceptionContext)
        {
            if (!SuppressNoLock)
            {
                command.CommandText =
                    TableAliasRegex.Replace(command.CommandText, "${tableAlias} WITH (NOLOCK)");
            }
        }
        /// <summary>
        /// ReaderExecuting
        /// </summary>
        /// <param name="command"></param>
        /// <param name="interceptionContext"></param>
        public override void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
        {
            if (!SuppressNoLock)
            {
                command.CommandText =
                    TableAliasRegex.Replace(command.CommandText, "${tableAlias} WITH (NOLOCK)");
            }
        }
    }
}
